﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;

namespace msBsc.WebUi
{
    public class PageCmdHandler : IHttpHandler,IRequiresSessionState
    {
        public PageCmdHandler()
        {
        }

        private string GetFormParam(string ParamName)
        {
            if (string.IsNullOrEmpty(HttpContext.Current.Request.Params[ParamName]))
                return string.Empty;
            else
                return HttpContext.Current.Request.Params[ParamName];
        }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.Cache.SetNoStore();
            doPageAjax(context);
        }

        private void doPageAjax(HttpContext context)
        {
            DateTime dtStart1 = DateTime.Now;
            string strPage = "", strParamJson = "", strPostJson = "", strPUrl = "";
            try
            {
                context.Response.Clear();


                if (!string.IsNullOrEmpty(context.Request.Params["PAGE"]))
                    strPage = context.Request.Params["PAGE"];
                if (!string.IsNullOrEmpty(context.Request.Params["JSPARAM"]))
                    strParamJson = context.Request.Params["JSPARAM"];
                if (!string.IsNullOrEmpty(context.Request.Params["JSPOST"]))
                    strPostJson = context.Request.Params["JSPOST"];
                msBsc.AppLogic.Cfg.SynDictionary htParam = gtJsonTo.GetHashData(strParamJson);
                msBsc.AppLogic.Cfg.SynDictionary htPostData = gtJsonTo.GetHashData(strPostJson);

                if (htParam != null && htParam["PPAGE"] != null)
                    strPage = htParam["PPAGE"].ToString();

                //if (strPage != "wfLogin")
                //{
                //    UserInfo oUserInfo = new UserInfo();
                //    if (!msBsc.SvRef.UserInfo.Online)
                //    {
                //        msBsc.WebUi.BPlogin owtem = new msBsc.WebUi.BPlogin();
                //        owtem.SetLogin(this, false);
                //        if (!msBsc.SvRef.UserInfo.Online)
                //        {
                //            throw new Exception("错误：用户未登录！");
                //        }
                //    }
                //}

                //if (!string.IsNullOrEmpty(context.Request.Params["F_UPLOAD"]))
                //{
                //    UPfile();
                //    return;
                //}


                string strJSon = "";
                //Type type1 = this.GetTypeInternal(typeName, false, ignoreCase, false);
                //if (type1 == null)
                //{
                //    return null;
                //}  
                Type otype = Type.GetType(strPage, false, false);
                if (otype != null)
                {
                    int itm1111 = strPage.LastIndexOf('.');
                    if (itm1111 != -1 && strPage.Substring(itm1111 + 1, 2) == "mf" || itm1111 == -1 && strPage.StartsWith("mf"))
                    {
                        using (msBsc.Cls.mbPage ocpage = (msBsc.Cls.mbPage)Activator.CreateInstance(otype))
                        {
                            strJSon = ocpage.GetJSon(htParam, htPostData);
                        }
                    }
                    else
                    {
                        using (msBsc.Cls.BPage ocpage = (msBsc.Cls.BPage)Activator.CreateInstance(otype))
                        {
                            strJSon = ocpage.GetJSon(htParam, htPostData);
                        }
                    }
                    GC.Collect();
                }
                else
                {
                    //strPUrl = context.Request.AppRelativeCurrentExecutionFilePath;
                    //if (strPUrl.StartsWith("~/"))
                    //{
                    //    strPUrl = strPUrl.Substring(2, strPUrl.Length - 2);
                    //}
                    //string cname = strPUrl.Substring(strPUrl.LastIndexOf("/") + 1, strPUrl.Length - (strPUrl.LastIndexOf("/") + 1));
                    //cname = cname.Substring(0, cname.LastIndexOf("."));
                    //System.Reflection.Assembly asm = System.Reflection.Assembly.Load("msBsc.WebUi");
                    System.Reflection.Assembly asm = System.Reflection.Assembly.GetExecutingAssembly();
                    //object frmObj = asm.CreateInstance("MC.Sales." + formName, true); 


                    Type[] types = asm.GetTypes();
                    IEnumerable<Type> asmType =
            types.Where((type, index) => type.Name.ToUpper() == strPage.ToUpper());
                    foreach (Type type in asmType)
                    {
                        int itm1111 = strPage.LastIndexOf('.');
                        if (itm1111 != -1 && strPage.Substring(itm1111 + 1, 2) == "mf" || itm1111 == -1 && strPage.StartsWith("mf"))
                        {
                            using (msBsc.Cls.mbPage ocpage = (msBsc.Cls.mbPage)type.Assembly.CreateInstance(type.FullName))
                            {
                                try
                                {
                                    strJSon = ocpage.GetJSon(htParam, htPostData);
                                    ocpage.Dispose();
                                    GC.Collect();
                                }
                                catch (Exception err)
                                {
                                    ocpage.Dispose();
                                    GC.Collect();
                                    throw err;
                                }
                            }
                        }
                        else
                        {
                            using (msBsc.Cls.BPage ocpage = (msBsc.Cls.BPage)type.Assembly.CreateInstance(type.FullName))
                            {
                                try
                                {
                                    strJSon = ocpage.GetJSon(htParam, htPostData);
                                    ocpage.Dispose();
                                    GC.Collect();
                                }
                                catch (Exception err)
                                {
                                    ocpage.Dispose();
                                    GC.Collect();
                                    throw err;
                                }
                            }
                        }
                        break;
                    }
                }
                context.Response.Write(strJSon);
                //try
                //{
                //    if (DateTime.Now > dtStart1.AddSeconds(15))
                //    {
                //        UserInfo oUserInfo2 = new UserInfo();
                //        oUserInfo2.LogUserOperate("执行超时ajc", strPage + strParamJson
                //            , System.DateTime.Now.ToString()
                //            , System.DateTime.Now.ToString()
                //            , HttpContext.Current.Request.UserHostAddress
                //            , HttpContext.Current.Request.UserHostName
                //            , HttpContext.Current.Request.UserAgent
                //            , (DateTime.Now - dtStart1).TotalSeconds.ToString() + "---" + dtStart1.ToString() + "-->--" + DateTime.Now.ToString());
                //    }
                //}
                //catch { }
            }
            catch (Exception err)
            {
                if (err.InnerException != null)
                {
                    err = err.InnerException;
                }
                string strlogin = "";
                if (err.Message.IndexOf("会话或服务器缓存已过期，请重新登录！")!=-1)
                {
                    strlogin = ",\"jscrip\":\"window.location.href =window.location.href;\"";
                }
                context.Response.Clear();
                context.Response.Write("[{");
                context.Response.Write(string.Format("\"jmsg\":\"{0}\"", msBsc.AppLogic.Cfg.HttpTools.stringToJson("服务器端错误：" + err.Message + "\r\n错误堆栈：" + err.Source)) + strlogin);
                context.Response.Write("}]");
            }
            context.Server.ClearError();
        }


        public bool IsReusable
        {
            get { return true; }
        }
    }
}